package com.treasure.mall.biz.base;

import com.treasure.mall.zbq.common.ienum.auth.RoleEnum;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Collection;

/**
 * @author allan
 * @version 1.0.0
 * @date 2020/6/12
 */
public class AuthHelper {
    public static boolean hasAnyRole(RoleEnum... roleEnums) {
        return false;
    }

    public static boolean hasRole(RoleEnum roleEnum) {
        Collection<? extends GrantedAuthority> collection = SecurityContextHolder.getContext().getAuthentication().getAuthorities();

        return collection.stream().anyMatch(p -> p.getAuthority().equals(roleEnum.getCode()));
    }

    /**
     * 得到当前登录用户
     *
     * @return
     */
    public static UserDetails getPrincipal() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null) {
            return (UserDetails) authentication.getPrincipal();
        }

        return null;
    }

    /**
     * 得到当前用户角色
     *
     * @return
     */
    public static RoleEnum getRole() {
        UserDetails userDetails = getPrincipal();
        if (userDetails == null) {
            return RoleEnum.MERCHANT;
        }
        return userDetails.getRoleType();
    }

    /**
     * 是否是商家角色
     *
     * @return
     */
    public static boolean isMerchant() {
        UserDetails userDetails = getPrincipal();
        return isMerchant(userDetails);
    }

    public static boolean isMerchant(UserDetails userDetails) {
        return userDetails != null && userDetails.getRoleType() == RoleEnum.MERCHANT;
    }

    /**
     * 是否是管理员角色
     *
     * @return
     */
    public static boolean isManager() {
        UserDetails userDetails = getPrincipal();
        return userDetails != null && userDetails.getRoleType() == RoleEnum.ADMIN;
    }

    /**
     * 是否是鉴定中心
     *
     * @return
     */
    public static boolean isOrg() {
        UserDetails userDetails = getPrincipal();
        return userDetails != null && userDetails.getRoleType() == RoleEnum.ORG_CENTER;
    }
}
